<template>
  <div class="port-area-list">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span>港口区域管理</span>
          <el-button type="primary" @click="handleAdd">新增区域</el-button>
        </div>
      </template>
      
      <el-table
        :data="portAreas"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column label="序号" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="区域编号" prop="areaCode" />
        <el-table-column label="区域名称" prop="areaName" />
        <el-table-column label="区域类型" prop="areaType" />
        <el-table-column label="最大容量" prop="maxCapacity" />
        <el-table-column label="当前使用" prop="currentUsage" />
        <el-table-column label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="handleView(scope.row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑港口区域对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="areaForm" label-width="100px" :rules="formRules" ref="areaFormRef">
        <el-form-item label="区域编号" prop="areaCode">
          <el-input v-model="areaForm.areaCode" placeholder="请输入区域编号"></el-input>
        </el-form-item>
        <el-form-item label="区域名称" prop="areaName">
          <el-input v-model="areaForm.areaName" placeholder="请输入区域名称"></el-input>
        </el-form-item>
        <el-form-item label="区域类型" prop="areaType">
          <el-select v-model="areaForm.areaType" placeholder="请选择区域类型">
            <el-option label="集装箱" value="集装箱"></el-option>
            <el-option label="散货" value="散货"></el-option>
            <el-option label="液体货" value="液体货"></el-option>
            <el-option label="冷藏区" value="冷藏区"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最大容量" prop="maxCapacity">
          <el-input-number v-model="areaForm.maxCapacity" :min="0" :precision="2" :step="100"></el-input-number>
        </el-form-item>
        <el-form-item label="当前使用量" prop="currentUsage">
          <el-input-number v-model="areaForm.currentUsage" :min="0" :precision="2" :step="100"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="areaForm.status" placeholder="请选择状态">
            <el-option label="可用" value="可用"></el-option>
            <el-option label="维护中" value="维护中"></el-option>
            <el-option label="已满" value="已满"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'PortAreaList',
  setup() {
    const store = useStore()
    const router = useRouter()
    const portAreas = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('新增港口区域')
    const areaFormRef = ref(null)
    
    // 港口区域表单数据
    const areaForm = reactive({
      areaId: null,
      areaCode: '',
      areaName: '',
      areaType: '集装箱',
      maxCapacity: 1000,
      currentUsage: 0,
      status: '可用'
    })
    
    // 表单验证规则
    const formRules = {
      areaCode: [
        { required: true, message: '请输入区域编号', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      areaName: [
        { required: true, message: '请输入区域名称', trigger: 'blur' }
      ],
      areaType: [
        { required: true, message: '请选择区域类型', trigger: 'change' }
      ],
      maxCapacity: [
        { required: true, message: '请输入最大容量', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    const fetchPortAreas = async () => {
      loading.value = true
      try {
        await store.dispatch('fetchPortAreas')
        portAreas.value = store.getters.portAreas
        console.log('获取到的港口区域数据:', portAreas.value)
      } catch (error) {
        console.error('获取港口区域失败:', error)
        ElMessage.error('获取港口区域失败')
      } finally {
        loading.value = false
      }
    }
    
    const getStatusType = (status) => {
      switch (status) {
        case '可用':
          return 'success'
        case '维护中':
          return 'warning'
        case '已满':
          return 'danger'
        default:
          return 'info'
      }
    }
    
    // 重置表单
    const resetForm = () => {
      areaForm.areaId = null
      areaForm.areaCode = ''
      areaForm.areaName = ''
      areaForm.areaType = '集装箱'
      areaForm.maxCapacity = 1000
      areaForm.currentUsage = 0
      areaForm.status = '可用'
      if (areaFormRef.value) {
        areaFormRef.value.resetFields()
      }
    }
    
    const handleAdd = () => {
      dialogTitle.value = '新增港口区域'
      resetForm()
      dialogVisible.value = true
    }
    
    const handleView = (area) => {
      router.push(`/port-areas/${area.areaId}`)
    }
    
    const handleEdit = (area) => {
      dialogTitle.value = '编辑港口区域'
      Object.assign(areaForm, area)
      dialogVisible.value = true
    }
    
    const handleDelete = (area) => {
      ElMessageBox.confirm(
        `确认删除港口区域"${area.areaName}"吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const response = await axios.delete(`/port-areas/${area.areaId}`)
          if (response.data.code === 200) {
            ElMessage.success('删除成功')
            fetchPortAreas()
          } else {
            ElMessage.error(response.data.message || '删除失败')
          }
        } catch (error) {
          console.error('删除港口区域失败:', error)
          ElMessage.error('删除港口区域失败')
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!areaFormRef.value) return
      
      try {
        await areaFormRef.value.validate()
        
        if (areaForm.areaId) {
          // 编辑现有区域
          const response = await axios.put(`/port-areas/${areaForm.areaId}`, areaForm)
          if (response.data.code === 200) {
            ElMessage.success('更新港口区域成功')
            dialogVisible.value = false
            fetchPortAreas()
          } else {
            ElMessage.error(response.data.message || '更新港口区域失败')
          }
        } else {
          // 新增区域
          const response = await axios.post('/port-areas', areaForm)
          if (response.data.code === 200) {
            ElMessage.success('添加港口区域成功')
            dialogVisible.value = false
            fetchPortAreas()
          } else {
            ElMessage.error(response.data.message || '添加港口区域失败')
          }
        }
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请检查表单填写是否正确')
      }
    }
    
    onMounted(() => {
      fetchPortAreas()
    })
    
    return {
      portAreas,
      loading,
      dialogVisible,
      dialogTitle,
      areaForm,
      areaFormRef,
      formRules,
      handleAdd,
      handleView,
      handleEdit,
      handleDelete,
      submitForm,
      getStatusType
    }
  }
}
</script>

<style scoped>
.port-area-list {
  padding: 20px;
}

.list-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>